#include "tmradar.h"
#include "tmglobaldef.h"

TmRadar::TmRadar(QObject *parent) : QObject(parent)
{
    m_pUdpSever = new QUdpSocket();
    m_strMAC = getLocalMac();
    g_strRobotMAC = m_strMAC;
    connect(m_pUdpSever, SIGNAL(readyRead()), this, SLOT(slot_new_udp()));
}

TmRadar::~TmRadar()
{
    m_pUdpSever->close();
}

QString TmRadar::getLocalMac()
{
    QString mac;
    QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();//获取所有网卡信息

    foreach(const QNetworkInterface &iface,ifaces)
    {
        if ( iface.flags().testFlag(QNetworkInterface::IsUp) && iface.flags().testFlag(QNetworkInterface::IsRunning) && !iface.flags().testFlag(QNetworkInterface::IsLoopBack))
        { //获取当前有效网卡
            mac = iface.hardwareAddress();
            //            if(iface.humanReadableName()=="以太网")
            break;
        }
    }

    if(mac.isEmpty()) { //有时候还是获取不到，所以默认获得主机IP
        foreach(const QNetworkInterface &iface,ifaces)
        {
            if(!iface.flags().testFlag(QNetworkInterface::IsLoopBack) /*&& iface.humanReadableName()=="以太网"*/) {
                mac = iface.hardwareAddress();
                break;
            }
        }
    }
    return mac;
}

void TmRadar::StartRadar()
{
    m_nUdpPort = g_pSettingCore->value("Server/Radar",6670).toInt();
    m_pUdpSever->bind(QHostAddress::Any, m_nUdpPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
}

void TmRadar::slot_new_udp()
{
    while( m_pUdpSever->hasPendingDatagrams() ){
        // recv and send
        QByteArray bCmdAll;
        QHostAddress clientAddr;
        quint16 clientPort;
        bCmdAll.resize(m_pUdpSever->pendingDatagramSize());
        m_pUdpSever->readDatagram(bCmdAll.data(), bCmdAll.size(), &clientAddr, &clientPort);
        // process
        if( bCmdAll.length()>13 ){
            if( bCmdAll.startsWith("Tami") && bCmdAll[12] == 'U' ){
                QString strCmd = bCmdAll.right(bCmdAll.length()-13);
                if( strCmd == "FindRobot" ){
                    QString strSendCmd = QString("Tami00000000U%1 %2 %3").arg(g_strRobotType).arg(g_strCoreVersion).arg(m_strMAC);
                    m_pUdpSever->writeDatagram(strSendCmd.toUtf8(), clientAddr, clientPort);
                }
            }
        }
    }
}
